// 'use strict';

import axios from 'axios';
// import store from '../store';
import { router } from '../main';
import { message } from 'ant-design-vue';
import { logout } from '@/services/user'

// Full config:  https://github.com/axios/axios#request-config
axios.defaults.baseURL = process.env.VUE_APP_API_BASE_URL;
// axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

let config = {
  // baseURL: process.env.baseURL || process.env.apiUrl || ""
  // baseURL: process.env.VUE_APP_API_BASE_URL
  // timeout: 60 * 1000, // Timeout
  // withCredentials: true // Check cross-site Access-Control
};

const _axios = axios.create(config);

_axios.interceptors.request.use(
  function (config) {
    const token = sessionStorage.getItem('token');
    if (token) {
      config.headers.Authorization = 'Bearer ' + token;
    }
    const socketId = sessionStorage.getItem('socket-id')
    if (socketId) {
      config.headers['x-socket-id'] = socketId
    }
    // Do something before request is sent
    return config;
  },
  function (error) {
    // Do something with request error
    return Promise.reject(error);
  }
);

// Add a response interceptor
_axios.interceptors.response.use(
  function (response) {
    // Do something with response data
    if (response.data.code == -2 || response.data.code == -3 || response.data.code == 401) {
      logout()
      message.error('验证失败，请重新登录');
      router.push('/login');
    }
    return response;
  },
  function (error) {
    console.log(error);
    return
    if (error.response.status == 401) {
      logout()
      router.push('/login')
      message.error('验证失败，请重新登录');
    }
    // Do something with response error
    return Promise.reject(error);
  }
);

export { _axios }

export default {
  install: (Vue, options) => {
    // console.log(options);
    // Vue.axios = _axios;
    Object.defineProperties(Vue.prototype, {
      axios: {
        get () {
          return _axios;
        }
      },
    })
  }

}
